<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html class="win-frame">
<head>
<title>${name_china}管理-编辑${name_china}</title>
<%@include file="/common/head.jsp" %>
<script src="<%=request.getContextPath()%>/static/layDate-v5.0.9/laydate/laydate.js"></script>
<style>
.addbtm{
	    margin: 0 auto;
	    position: relative;
	    width: 100px;
	    height: 36px;
	    line-height: 36px;
	    text-align: center;
	    color: #fff;
	    margin-left: 174px;
	    margin-top: 10px;
	}
</style>
</head>
<body class="iframe-page">
<div class="page-title-wrapper">
    <div class="page-title">
        <div class="page-title-text">
            <span>${name_china}管理</span>
            <span class="split"></span>
            <span>编辑${name_china}</span>
        </div>
        <a id="goBack" class="btn-return distance-left" href="javascript:;"><i class="icon icon-arrow-left"></i>返回上级</a>
    </div>
    <div class="page-title-border"></div>
</div>

<form id="form" method="post">
    <div class="form-wrapper">
	  <div class="h4 distance-double">
        <span class="h4-title"><i class="icon icon-setting"></i>已上传素材</span>
        <span class="h4-border"></span>
      </div>
      <div id="setedData"> 
      </div> 
	     <div class="h4 distance-double">
	        <span class="h4-title"><i class="icon icon-setting"></i>设置素材</span>
	        <span class="h4-border"></span>
	      </div>
	      
	      <div class="form-cont">
	        <p class="form-cont-title">设置类型</p>
	        <input type="hidden" id="userId" name="userId"/>
	        <input type="hidden" id="clientId" name="clientId">
	        <input type="text" id="timerType" name="timerType" class="summer-input summer-validatebox"  data-validatebox="validType:['required']"/> 
	     </div>
	     <div class="form-cont">
	        <p class="form-cont-title">类型</p>
	        <input type="text" id=type name="type" class="summer-input summer-validatebox"  data-validatebox="validType:['required']"/> 
	     </div>
	     <div id="seperate">
	      <div class="form-cont">
	        <p class="form-cont-title">间隔时间（分钟）</p>
	        <input type="text" id="min" name="min" class="summer-input summer-validatebox"/> 
	     </div>
	     </div>
		 <div id="video">
	     <div class="form-cont">
	        <p class="form-cont-title">上传视频</p>
	        <input type="hidden" id="videoUrl" name="videoUrl" class="summer-input summer-validatebox"/> 
	     </div>
	     </div>
	    <div id="add">
	    <div  class="addbtm">
		<a class="btn btn-normal" id="addTime">添加时间段 +</a>
		</div>
		
		</div>
	     <div id="self">
	     <div class="form-cont">
	     <p class="form-cont-title">自定义开始时间</p>
	     <input type="text" id="sTime0" name="sTime0" class=" summer-input summer-validatebox" />
	     <input type="hidden" id="startTime" name="startTime" />
	     <input type="hidden" id="timeNum" name="timeNum" value="1"/>
	     </div>
	     <div class="form-cont">
	     <p class="form-cont-title">自定义结束时间</p>
	     <input type="hidden" id="endTime" name="endTime" />
	     <input type="text" id="eTime0" name="eTime0" class=" summer-input summer-validatebox" />
	     </div>
	     </div>
	     
         <div class="form-btn-wrapper" id="funcbar">
        <a class="btn btn-normal" id="backBtn">关闭</a>
    </div>
  </div>
</form>
<form id="releaseForm">
	<div id="showGoods">
        <div class="form-cont">
	     <p class="form-cont-title">时间</p>
	      <input type="text" id="timeId" name="timeId" class="summer-input summer-validatebox"/>
	     </div>
        <div class="form-cont" id="goods">
		</div>
	     <input type="hidden" name="spuIds" id="spuIds"/>
	     <input type="hidden" id="userID" name="userID"/>
	     <input type="hidden" name="delSpuIds" id="delSpuIds"/>
	<div class="form-btn-wrapper" id="funcbarf">
        <a class="btn btn-normal" id="backBtnf">关闭</a>
    </div>
	</div>
</form>
<div id="chooseGoods">
<div id="searchF" class="search-field">
	<span class="field-cont">
        <span class="field-cont-title">商品名称</span>
        <input type="text" class="summer-input" id="goodsName"/>
    </span>
    
    <span class="field-cont">
        <span class="field-cont-title">商品平台类型</span>
        <input type="text" id="spuPlatform" name="spuPlatform" class="summer-input summer-validatebox"  data-validatebox="validType:['maxLength[20]']"/> 
    </span>
    
     <span class="field-cont">
        <span class="field-cont-title">商品分类</span>
        <input type="text" id="categoryId" name="categoryId" class="summer-input summer-validatebox"  data-validatebox="validType:['required','maxLength[500]']"/> 
    </span><br/>
   
     <span class="field-cont">
        <span class="field-cont-title">是否爆款</span>
        <input type="text" class="summer-input" id="isHot"/>
    </span><br/>
    <span class="field-btn-wrapper">
        <a id="search" class="btn btn-primary btn-icon wave distance-right"><i class="icon icon-search"></i></a>
        <a id="reset" class="btn btn-icon wave wave-dark"><i class="icon icon-refresh"></i></a>
        <a id="addSpus" class="btn btn-primary  wave distance-right">设置为展示商品</a>
    </span>
    </div>
    
<div id="t-wrap">
    <table class="summer-datagrid" id="dataList">
	    <col width="10%">
	    <col width="30%">
	    <col width="20%">
	    <col width="20%">
	    <col width="20%">
	    <col width="20%">
	    <col width="25%">
	    <thead>
		     <tr>
		    <th><div class="summer-datagrid-cell"></div></th>
		    <th><div class="summer-datagrid-cell">名称</div></th>
		    <th><div class="summer-datagrid-cell">图片</div></th>
		    <th><div class="summer-datagrid-cell">类型</div></th>
		    <th><div class="summer-datagrid-cell">分类</div></th>
		    <th><div class="summer-datagrid-cell">价钱（原价、券后价、佣金数）</div></th>
		    <th><div class="summer-datagrid-cell">时间</div></th>
			 </tr>
	    </thead>
    </table>  
</div>
</div>
<script>
    
  var   editData,
  		goodsData,
  		i = 1,
  		j = 0,
  		addgoods = "",
  		goodsID = "",
        permission = CommonUtil.getPermission('${name_english}');
    
    $(function () {
    	editData = ${editData};
    	goodsData = ${goodsData};
    	//上传视频文件
    	$("#video").hide();
    	$("#videoUrl").filePlugin();
    	//已上传素材展示
    	if(editData != "null"){
    		var setHtml = "";
    		for(var n=0;n<editData.length;n++){
    			setHtml = setHtml
    					 + '<p>'+editData[n].startTime + "~" + editData[n].endTime + '&nbsp;' + editData[n].type+'</p>';
    		}
    		$("#setedData").append(setHtml);
    	}
    	goodsID = goodsID + $("#spuIds").val();//将商品id累积
    	$("#userId").val(${userId});
    	$("#clientId").val(${clientId});
    	$("#userID").val(${userId});
    	//初始化自定义时间控件
    	laydate.render({
    		elem: '#sTime0',
    		type: 'time'
    	});
    	laydate.render({ 
	        elem: '#eTime0',
	        type: 'time'
	    });
	    //初始化间隔为隐藏
	    $("#seperate").hide();
    	//初始化funcbar
     	$('#funcbar').prepend($.funcbar({
            type: 'button',
            data: permission,
            permit: ['${name_english}:insertTime']
        }));
    	
     	$('#funcbarf').prepend($.funcbar({
            type: 'button',
            data: permission,
            permit: ['${name_english}:release','${name_english}:delGoods']
        }));
   	 	//添加时间按钮
   	 	var count = 0;
   	 	$("#addTime").on('click',function(){
   	     	var html = '<div class="form-cont">'
   		      	   +'<p class="form-cont-title">自定义开始时间</p>'
   	  		   +'<input type="text" id="sTime'+i+'" name="sTime'+i+'" class=" summer-input summer-validatebox" />' 
   				   +'</div>'
   				   +'<div class="form-cont">'
   	 		   +'<p class="form-cont-title">自定义结束时间</p>' 
   	            +'<input type="text" id="eTime'+i+'" name="eTime'+i+'" class=" summer-input summer-validatebox" />' 
   				   +'</div>';
   	 		$("#self").append(html);
   	 			laydate.render({ 
     	   		elem: '#sTime'+i+'',
     	   		type: 'time'
     		});
     		laydate.render({ 
       	  		elem: '#eTime'+i+'',
       	  		type: 'time'
       		});
     		count = i++;
       	 	$("#timeNum").val(i);
   	 	});
   	 	//时间添加次数计数
     	//下拉初始化
    	 $('#isHot').combobox({
             valueField : 'code',
             textField : 'name',
             url : COMMON_URL.getCode + '?type=T_DM_T_GOODS_SPU_IS_HOT'
         });
    	 $('#categoryId').combobox({
             url : CONST_URL.GET_GOODS_CATEGORY, 
             valueField : 'id',
             async:false,
             textField : 'name'
         });
    	 $('#timeId').combobox({
             url : CONST_URL.GET_TIMER+"?userId="+$("#userId").val(), 
             valueField : 'id',
             async:false,
             textField : 'startTime'
         });
    	 $('#spuPlatform').combobox({
             valueField : 'code',
             textField : 'name',
             url : COMMON_URL.getCode + '?type=T_DM_T_GOODS_SPU_SPU_PLATFORM'
         });
    	 //下拉列表初始化，上传类型
    	$('#type').combobox({
   	    	defaultValue:'goods',
   	    	async:false,
            valueField : 'code',
            textField : 'name',
            url : COMMON_URL.getCode + '?type=T_DM_T_YWYM_TIMER_TYPE',
            onSelect : function (record){
            	if("video" == record.code){
            		$("#video").show();
            		$("#chooseGoods").hide();
            	}
            	if("goods" == record.code){
            		$("#video").hide();
            		$("#chooseGoods").show();
            	}
            }
    	});
    	 //设置时间类型下拉列表
   	    $('#timerType').combobox({
   	    	defaultValue:'custom',
   	    	async:false,
            valueField : 'code',
            textField : 'name',
            url : COMMON_URL.getCode + '?type=T_DM_YWYM_TIMER_TYPE',
            onSelect : function (record){
            	//自定义,展示可选时间
            	if( "custom"==record.code ){
            		//时间选择器
            		$("#self").show();
            		$("#add").show();
            		$("#seperate").hide();
            	}
            	//素材间隔
            	if("persistent" == record.code){
            		$("#self").hide();
            		$("#add").hide();
            		$("#seperate").show();
            	}	
            }
        }); 
     	 //加载数据
     	 $('#form').form({
        	onLoadSuccess:function(data){
            }
         }).form('loadDataEdit', {
            data: editData
         });
     	 
    	 //增加时间
    	 $('#funcbar').on('click', 'a[data-permit="${name_english}:insertTime"]', submit);
    	 //发布
    	 $('#funcbarf').on('click', 'a[data-permit="${name_english}:release"]', Rsubmit);
    	 //删除商品
    	 $('#funcbarf').on('click', 'a[data-permit="${name_english}:delGoods"]', function(){
    		 var delSpuIds = "",
    		 spuIds = $("#spuIds").val(),
    		 userId = $("#userId").val();
    		 //获取删除商品编号
    		 for(var k=0;k<goodsData.length;k++){
    			 if($("#spuID"+k+"").is(':checked')){
    				 if(delSpuIds == ""){
    					 delSpuIds = $("input[name='spuID"+k+"']:checked").attr('value');
    				 }else{
        				 delSpuIds = delSpuIds + "," + $("input[name='spuID"+k+"']:checked").attr('value');
    				 }
    			 }
    		 }
    		 $("#delSpuIds").val(delSpuIds);
    		 var delIds = $("#delSpuIds").val();
    		 window.location.href = CONST_URL.DEL_GOODS+"?spuIds="+spuIds+"&userId="+userId+"&delIds="+delIds
    	 });
    	 

    	 //返回按钮
    	 $('#backBtn, #goBack,#backBtnf').on('click',backMain);
    	 $('#search').on('click', reloadTable);
    	//设置为展示商品
     	$('#addSpus').on('click',function(){
     		//商品展示栏增加展示商品
     		//选中内容：商品ID,商品名称,商品图片#
     		var spuId = $("input[name='spuId']:checked").serialize();
     		
     		spuId = spuId + goodsID;
     		var userId = $("#userId").val();
     		window.location.href = CONST_URL.ADD_GOODS+"?spuId="+spuId+"&userId="+userId
     	});
		$("#showGoods").hide();
    	//展示商品
    	if(goodsData != "null"){
    		var Gdata = "";
    		for(var k=0;k<goodsData.length;k++){
    			Gdata = Gdata + '<div style="float:left;width:20%;">'
 				   +'<input type="hidden" id="spuId'+k+'" value="'+goodsData[k].id+'">'
 				   +'<div style="width:148px;height:148px"><img style="width:100%;height:100%;" src="'+goodsData[k].mainImageUrl+'"></div>'
 				   +'<div style="width:90%;height:100px;"><p>'+goodsData[k].goodsName+'</p></div>'
 				   +'<input type="checkbox" id="spuID'+k+'" name="spuID'+k+'" value="'+goodsData[k].id+'">'
 				   +'</div>';
    			goodsID = goodsID +","+ goodsData[k].id;//将已设置展示的商品ID编号累计
    		}
    		$("#goods").append(Gdata);
    		//商品编号列表
    		$("#spuIds").val(goodsID);
    		$("#showGoods").show();
    	}
    	
      	 $('#reset').on('click', function() {
 			//重置文本框的值
 			$('#goodsName').val('');
 			$('#spuPlatform').combobox('clear');
 			$('#categoryId').combobox('clear');
 			$('#isHot').combobox('clear');
 			reloadTable();
 		});
    	 //加载商品列表
    	 createTable();
    });
  //增加时间
    function submit() {
		//获取已选中商品id
     	//时间创建个数i
     	var setedTime = "";
     	var num = $("#timeNum").val();
     	var startTime = "";
     	var endTime = "";
		for(var m=0;m<num;m++){
			if(startTime == ""){
				startTime = $('#sTime'+m+'').val();
			}else{
				startTime = startTime + ","+ $('#sTime'+m+'').val();
			}
			if(endTime == ""){
				endTime = $('#eTime'+m+'').val();
			}else{
				endTime = endTime + ","+ $('#eTime'+m+'').val();
			}
		}
		$("#startTime").val(startTime);
		$("#endTime").val(endTime);
    	$("#form").form({
        	 buttons : ['#saveBtn'],
             ajax: {
                 url: CONST_URL.INSERT_TIME
             },
             onSubmitSuccess: function (data) {
            	 if(data.msg != "null"){
            		 alert(data.msg);
            	 }else{
            		 $.stip({
        	                type:'ok',//显示类型 有info、 ok、 danger
        	                text: '增加时间成功成功！',
        	                onBeforeHide: function () {
        	                	var clientId = $("#clientId").val();
           	                	window.location.href = CONST_URL.INIT_MATERIAL+"?id="+clientId;
        	                }
                 	 });
            	 }
              }
         }).form("submit");
    }
    
    // 重新加载表格
	function reloadTable() {
		$('#dataList').datagrid('reload', {
			ajax : {
				param : {
					"goodsName": trimSpace($('#goodsName').val()),
					"spuPlatform": $('#spuPlatform').combobox('getValue'),
					"categoryId": $('#categoryId').combobox('getValue'),
					"isHot": $('#isHot').combobox('getValue'),
					"userId": trimSpace($('#userId').val())
				}
			}
		});
	}
    //商品列表展示
    //创建表格
	function createTable() {
		$('#dataList')
				.datagrid(
						{
							ajax : {
								url : CONST_URL.GOODS_LIST,
								param : {	
									"goodsName": trimSpace($('#goodsName').val()),
									"spuPlatform":$('#spuPlatform').combobox('getValue'),
									"categoryId":$('#categoryId').combobox('getValue'),
									"isHot":$('#isHot').combobox('getValue'),
									"userId": trimSpace($('#userId').val())
								},
								success : function(data) { //成功 
									alert("Data Saved: " + msg);
								}
							},
							columns : [
									{
										render : function(rowData){
											return '<input type="checkbox" id="spuId" name="spuId" value="'+rowData.spuId+'">';
										}
									},
									{
										field : 'goodsName'
									},
									{
										field: 'mainImageUrl',
										render : function(rowData){
											return '<img width="100" height="100" src="'+rowData.mainImageUrl+'">';
										}
									},
									{
										field : 'spuPlatform'
									},
									{
										field : 'categoryId'
									},
									{
										render : function(rowData){
											return '<p>原价：'+rowData.wlPrice+'</p><br/>'
												  +'<p>券后价：'+rowData.conPrice+'</p><br/>'
												  +'<p>佣金：'+rowData.wlCommission+'</p>';
										}
									},
									{
										field : 'createTime'
									}
							]
						});
	}
    //发布
    function Rsubmit(){
    	$("#releaseForm").form({
       	 buttons : ['#saveBtn'],
            ajax: {
                url: CONST_URL.RELEASE
            },
            onSubmitSuccess: function (data) {
           	 if(data.msg != "null"){
           		 alert(data.msg);
           	 }else{
           		 $.stip({
       	                type:'ok',//显示类型 有info、 ok、 danger
       	                text: '发布成功！',
       	                onBeforeHide: function () {
       	                	var userId = $("#userId").val();
       	                	window.location.href = CONST_URL.INIT_MATERIAL+"?clientId="+clientId;
       	                }
                	 });
           	 }
             }
        }).form("submit");
    }
    
    //返回主页面
    function backMain() {
    	window.location.href = CONST_URL.INIT_MAIN;
    }
    
    //请求url
    var CONST_URL = {
    	INIT_MAIN: basePath + "${common_url}init",
       	EDIT: basePath + "${common_url}edit",
       	GOODS_LIST: basePath + "${common_url}goodsList",
       	GET_GOODS_CATEGORY: basePath + "${common_url}getGoodsCategory",
       	ADD_GOODS: basePath + "${common_url}addGoods",
       	DEL_GOODS: basePath + "${common_url}delGoods",
       	RELEASE: basePath + "${common_url}release",
       	INIT_MATERIAL: basePath + "${common_url}initMaterial",
       	INSERT_TIME: basePath + "${common_url}insertTime",
       	GET_TIMER: basePath + "${common_url}getTimer"
    };
    
</script>
</body>
</html>